/**
 * Created by baiguiren on 2/10/17.
 */
let config = require('../config');
let QueryBuilder = require('knex/lib/query/builder'); //builder添加分页方法paginate

Object.assign(QueryBuilder.prototype, {
  paginate: function(per_page = config.api_page_size, current_page, columns = ['*']) {
    let pagination = {};
    //current_page = current_page || global.query.page;
    //per_page = +per_page || config.api_page_size;
    let page = +current_page || 1;
    if ( page < 1 ) page = 1;
    let offset = (page - 1)  * per_page;
    return Promise.all([
      this.clone().count('* as count').first(),
      this.columns(columns).offset(offset).limit(per_page)
    ]).then(function(values) {
      let count = values[0].count;
      let rows = values[1];
      pagination.data = rows;
      pagination.total_count = count;
      pagination.page_size = per_page;
      //pagination.offset = offset;
      //pagination.to = offset + rows.length;
      //pagination.last_page = Math.ceil(count / per_page);
      pagination.page = page;
      //pagination.from = offset;
      return pagination;
    }).catch(function (error) {
      console.log(error);
    })
  }
});

let knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'testkollway',
    password : 'testkollway',
    database : 'shells'
  },
  pool: { min: 0, max: 7 }
});


exports.knex = knex;